package com.dg11185.nearshop.activity.home;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.nearshop.R;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.activity.shop.ShopListActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.StaticData;
import com.wlper.lib.uitls.ViewUtils;

/**
 * 搜索界面
 * 
 * @author wanliang527
 * @date 2014-4-28
 */
public class SearchActivity extends SubPageActivity {
    private final static int MSG_READ_OVER = 23; // 读取搜索记录结束标识
    private final static int MSG_WRITE_OVER = 24;// 存储搜索记录结束标识
    private final static int MAX_KEY_COUNTS = 21;// 存储搜索关键词的最大数量

    private final static String KEY_SPLIT = "_";// 本地持久化存储搜索关键词时，搜索关键词之间的分隔标识
    private final static String CLEAR_HIS = "--清除搜索记录--";// 清除搜索记录

    // private EditText mEditText;
    private AutoCompleteTextView mEditText;
    private Button searchBtn;
    private GridView mGridView;
    private ArrayAdapter<String> mEditTextAdapter;
    private LinkedList<String> keyWords = new LinkedList<String>();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_READ_OVER:
                    mEditTextAdapter.notifyDataSetChanged();
                    break;
                case MSG_WRITE_OVER:
                    mEditTextAdapter.notifyDataSetChanged();
                    break;

                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
    }

    private void initView() {
        setSubPageTitle("搜索商家");
        // mEditText = (EditText) findViewById(R.id.edit_text_search_words);
        mEditText = (AutoCompleteTextView) findViewById(R.id.edit_text_search_words);
        keyWords.addLast(CLEAR_HIS);
        mEditTextAdapter = new ArrayAdapter<String>(mActivity,
                R.layout.view_simple_list_item, keyWords);
        mEditText.setDropDownAnchor(R.id.edit_text_search_words);
        mEditText.setDropDownHeight(300);
        mEditText.setDropDownWidth(300);
        mEditText.setDropDownVerticalOffset(10);
        mEditText.setDropDownBackgroundResource(R.color.white);
        mEditText.setAdapter(mEditTextAdapter);
        mEditText.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                TextView v = null;
                if (view instanceof TextView)
                    v = (TextView) view;
                if (v != null) {
                    String s = v.getText().toString();
                    if (s.equals(CLEAR_HIS)) {
                        keyWords.clear();
                        keyWords.addLast(CLEAR_HIS);
                        mEditTextAdapter.notifyDataSetChanged();
                        mPreferences.edit().putString(Constants.SEARCH_HIS, "")
                                .commit();
                        mEditText.setText("");
                    } else {
                        search(s);
                    }
                }
            }

        });
        mEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AutoCompleteTextView view = (AutoCompleteTextView) v;
                if (view.isPopupShowing()) {
                    view.dismissDropDown();
                } else {
                    view.showDropDown();
                }
            }
        });
        new ReadSearchHis().start();

        searchBtn = (Button) findViewById(R.id.btn_search);
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String keywords = mEditText.getText().toString();
                search(keywords);
            }
        });
        mGridView = (GridView) findViewById(R.id.grid_v_hot_words);
        mGridView
                .setAdapter(new GridViewAdapter(this, StaticData
                        .getSearchHotWords(), R.layout.view_grid_v_item,
                        new String[] { "HotWords" },
                        new int[] { R.id.txt_v_grid_item }));
    }

    /**
     * 读取搜索历史的线程。
     * 
     * @author wanliang527
     * 
     */
    private class ReadSearchHis extends Thread {
        @Override
        public void run() {
            super.run();
            String str = mPreferences.getString(Constants.SEARCH_HIS, "");
            if (!str.equals("")) {
                Message msg = new Message();
                msg.what = MSG_READ_OVER;
                keyWords.clear();
                String[] keys = str.split(KEY_SPLIT);
                for (int i = 0; i < keys.length; i++)
                    keyWords.addFirst(keys[i]);
                keyWords.addLast(CLEAR_HIS);
                mHandler.sendMessage(msg);
            }
        }
    }

    /**
     * 存储搜索历史的线程
     * 
     * @author wanliang527
     * 
     */
    private class SaveSearchHis extends Thread {

        private String key;// 关键词

        SaveSearchHis(String k) {
            key = k;
        }

        @Override
        public void run() {
            super.run();
            // 如果已有的数据集合中已经包括该关键词，就不做任何动作
            if (isContains(key))
                return;
            // 这一块代码可能会出现同步问题，因此引入同步代码块
            synchronized (this) {
                keyWords.addFirst(key);
                if (!isContains(CLEAR_HIS))
                    keyWords.addLast(CLEAR_HIS);
                int aa = keyWords.size() - MAX_KEY_COUNTS;
                if (aa > 0) {
                    for (int i = 0; i < aa; i++)
                        keyWords.remove(keyWords.size() - 2);
                }
                mPreferences.edit()
                        .putString(Constants.SEARCH_HIS, list2String(keyWords))
                        .commit();
                Message msg = new Message();
                msg.what = MSG_WRITE_OVER;
                mHandler.sendMessage(msg);
            }
        }

    }

    /**
     * 执行搜索的动作
     * 
     * @param keywords
     *            关键词
     */
    public void search(String keywords) {
        if (keywords == null || keywords.trim().equals("")) {
            Toast.makeText(this, "关键词不同为空", Toast.LENGTH_SHORT).show();
            return;
        }
        new SaveSearchHis(keywords).start();
        // save(keywords);
        Intent intent = new Intent(this, ShopListActivity.class);
        intent.putExtra("tag", ShopListActivity.SEARCH_LIST);
        intent.putExtra("merchantName", keywords);
        startActivity(intent);
        // this.finish();
    }

    private void save(String s) {
        if (isContains(s))
            return;
        keyWords.addFirst(s);
        if (!isContains(CLEAR_HIS))
            keyWords.addLast(CLEAR_HIS);
        int aa = keyWords.size() - MAX_KEY_COUNTS;
        if (aa > 0) {
            for (int i = 0; i < aa; i++)
                keyWords.remove(keyWords.size() - 2);
        }
        mPreferences.edit()
                .putString(Constants.SEARCH_HIS, list2String(keyWords))
                .commit();
        mEditTextAdapter.notifyDataSetChanged();
    }

    /**
     * 遍历关键词集合，查看是否含有特定关键词
     * 
     * @param k
     * @return 如果有返回true，并且停止遍历；遍历结束后，返回false；
     */
    public boolean isContains(String k) {
        Iterator<String> i = keyWords.iterator();
        while (i.hasNext()) {
            String s = i.next();
            if (s.equals(k))
                return true;
        }
        return false;
    }

    /**
     * 将字符串集合转换为带有特定界定符的一整串字符，便于本地持久化存储
     * 
     * @param list
     * @return
     */
    private String list2String(List<String> list) {
        StringBuilder sBuilder = new StringBuilder();
        for (int i = list.size() - 1; i >= 0; i--) {
            if (!list.get(i).equals(CLEAR_HIS)) {
                sBuilder.append(list.get(i));
                if (i != 0)
                    sBuilder.append(KEY_SPLIT);
            }
        }
        return sBuilder.toString();
    }

    /**
     * 显示快捷搜索关键词的适配器
     * 
     * @author wanliang527
     * 
     */
    private class GridViewAdapter extends SimpleAdapter {
        private int mResource;
        private List<? extends Map<String, ?>> mData;
        private String[] mFrom;
        private int[] mTo;
        private LayoutInflater mInflater;

        public GridViewAdapter(Context context,
                List<? extends Map<String, ?>> data, int resource,
                String[] from, int[] to) {
            super(context, data, resource, from, to);
            mResource = resource;
            mData = data;
            mFrom = from;
            mTo = to;
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return createViewFromResource(position, convertView, parent,
                    mResource);
        }

        private View createViewFromResource(int position, View convertView,
                ViewGroup parent, int resource) {
            View v;
            if (convertView == null) {
                v = mInflater.inflate(resource, parent, false);
            } else {
                v = convertView;
            }
            v.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (v instanceof TextView) {
                        String keywords = "";
                        if (v instanceof TextView) {
                            keywords = ((TextView) v).getText().toString();
                        }
                        search(keywords);
                    }

                }
            });
            ;
            bindView(position, v);

            return v;
        }

        private void bindView(int position, View view) {
            final Map dataSet = mData.get(position);
            if (dataSet == null) {
                return;
            }

            final ViewBinder binder = super.getViewBinder();
            final String[] from = mFrom;
            final int[] to = mTo;
            final int count = to.length;

            for (int i = 0; i < count; i++) {
                final View v = view.findViewById(to[i]);
                if (v != null) {
                    final Object data = dataSet.get(from[i]);
                    String text = data == null ? "" : data.toString();
                    if (text == null) {
                        text = "";
                    }

                    boolean bound = false;
                    if (binder != null) {
                        bound = binder.setViewValue(v, data, text);
                    }

                    if (!bound) {
                        if (v instanceof Checkable) {
                            if (data instanceof Boolean) {
                                ((Checkable) v).setChecked((Boolean) data);
                            } else if (v instanceof TextView) {
                                setViewText((TextView) v, text);
                            } else {
                                throw new IllegalStateException(
                                        v.getClass().getName()
                                                + " should be bound to a Boolean, not a "
                                                + (data == null ? "<unknown type>"
                                                        : data.getClass()));
                            }
                        } else if (v instanceof TextView) {
                            setViewText((TextView) v, text);
                        } else if (v instanceof ImageView) {
                            if (data instanceof Integer) {
                                setViewImage((ImageView) v, (Integer) data);
                            } else {
                                setViewImage((ImageView) v, text);
                            }
                        } else {
                            throw new IllegalStateException(
                                    v.getClass().getName()
                                            + " is not a "
                                            + " view that can be bounds by this SimpleAdapter");
                        }
                    }
                }
            }
        }

        public void setViewImage(ImageView v, int value) {
            v.setImageResource(value);
        }

        public void setViewImage(ImageView v, String value) {
            try {
                v.setImageResource(Integer.parseInt(value));
            } catch (NumberFormatException nfe) {
                v.setImageURI(Uri.parse(value));
            }
        }

        public void setViewText(TextView v, String text) {
            v.setText(text);
        }

    }

}
